package cs342.uwosh.edu.MyWorldApp.cloud;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.res.Resources;
import cs342.uwosh.edu.R;
import cs342.uwosh.edu.MyWorldApp.misc.AsyncMethod;
import cs342.uwosh.edu.MyWorldApp.storage.Location;
import cs342.uwosh.edu.MyWorldApp.storage.Place;

public class PlacesHandler {
	
	public PlacesHandler () {
		
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Place> getPlaces(Location loc) {
		String urlSearch = "https://maps.googleapis.com/maps/api/place/search/json?" +
				"location=" + loc.getLongitude() +"," +loc.getLatitude() +"&" +
				"radius=100&" +
				"types=campground|airport|police|hospital|food|bakery|bar|art_gallary|cafe|bus_station|zoo&" +
				"sensor=false&" +
				"key=" + Resources.getSystem().getString(R.string.googleMapsAPIKey);
		
		//Thread connects through google's api to retrieve places
		AsyncMethod<PlacesHandler> thread = new AsyncMethod<PlacesHandler>(PlacesHandler.class, this, "retrieveJSONData");
		thread.execute(urlSearch);
		JSONObject json = (JSONObject) thread.getResult();
		if(json != null) {
			// thread that parses JSON
			thread.setMethod("parseJSONObject");
			thread.execute(json);
			return (ArrayList<Place>) thread.getResult();
		} else {
			return null;
		}
	}
	
	// Retrieves a JSON Object
	public JSONObject retrieveJSONData(String urlSearch) {
		URL url;
		HttpURLConnection connection = null;
		StringBuffer response = new StringBuffer();
		try{
	        url = new URL(urlSearch);
	        connection = (HttpURLConnection)url.openConnection();
	        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	        String line;
	        while((line = in.readLine()) != null) {
	            response.append(line);
	        }
	        in.close();
	    }
	    catch(Exception e){   
	          e.printStackTrace();
	    } 
	    finally{   
	        if(connection != null) 
	            connection.disconnect();
	    }
		try {
			return new JSONObject(response.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	//Parses a JSONObject into Places
	
	public ArrayList<Place> parseJSONObject(JSONObject json) {
		ArrayList<Place> places = new ArrayList<Place>();
		try {
			double lat, lng;
			String icon;
			String name;
			String address;
			JSONObject obj, loc;
			JSONArray results = json.getJSONArray("results");
			for(int i = 0; i < results.length(); i++) {
				obj = results.getJSONObject(i);
				loc = obj.getJSONObject("geometry").getJSONObject("location");
				lat = loc.getDouble("lat");
				lng = loc.getDouble("lng");
				name = obj.getString("name");
				address = obj.getString("vicinity");
				//TODO get drawable icon
				icon = obj.getString("icon");
				places.add(new Place(name,address,lng,lat));
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return places;
	}
	
	
}
